package com.mofeng.myshop.domain.vo.base;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageMp<Vo> implements Serializable {

    private Collection<Vo> content = new ArrayList<>();
    private boolean empty;
    private boolean first;
    private boolean last;
    private long size;
    private long page;
    private long totalPages;
    private long totalCount;

    public PageMp(Page<Vo> page) {
        this.content = page.getRecords();
        setArr(page);
    }

    public <Po> PageMp(Page<Po> page, Function<Po, Vo> change) {
        this.content = page.getRecords().stream().map(change).collect(Collectors.toList());
        setArr(page);
    }

    public PageMp(Page page, List<Vo> content) {
        this.content = content;
        setArr(page);
    }

    /**
     * 设置属性
     */
    private void setArr(Page page) {
        this.empty = page.getRecords().isEmpty();
        this.page = page.getCurrent();
        this.size = page.getSize();
        this.totalCount = page.getTotal();
        this.totalPages = getPageCounts(this.size, this.totalCount);
        this.first = (this.page - 1) <= 0 || this.totalCount == 0;
        this.last = (this.page >= this.totalPages) || this.totalCount == 0;
    }

    /**
     * 获取总页数
     *
     * @return 总页数
     */
    private long getPageCounts(long size, long num) {
        return num % size == 0 ? num / size : num / size + 1;
    }
}